﻿<%@ Page Title="Promotion Engine -  Customer" Language="C#" MasterPageFile="~/Site.Master"
    AutoEventWireup="true" CodeBehind="Customer.aspx.cs" Inherits="PromotionEngine.Customer" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        var oCustomer = {};
        var isInsert = false;
        var grid;
        var jsonCustomerGrade
        var keySearch='',keyWords='';
        function GetCustomerGrade() {
            $.ajax({
                type: "GET",
                url: "CustomerGrade.aspx/GetCustomerGradeList",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    jsonCustomerGrade = $.parseJSON(data.d)
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function Search() {
            keySearch = $("#KeySearch").val();
            keyWords = $("#KeyWords").val();
            grid.dataSource.read();
        }
        $(document).ready(function () {
        $("#KeySearch").keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    Search();
                    return false;
                }
            });
            $("#KeyWords").keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    Search();
                    return false;
                }
            });
            keySearch = $("#KeySearch").val();
            keyWords = $("#KeyWords").val();
             GetCustomerGrade();
             grid = $("#grid").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            type: "GET",
                            url: "Customer.aspx/GetODataCustomerList1",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },
                        parameterMap: function (options, operation) {
                            if (operation === "read") {
                                return {
                                    keySearch: kendo.stringify(keySearch), 
                                    keyWords: kendo.stringify(keyWords) 
                                };
                            }
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    pageSize: 20,
                    type: "odata", //Important!!!!
                    schema: {
                         data: function (response) {
                            if (response.d != null && response.d != '') {
                                return JSON.parse(response.d);
                            }
                        },
                        total: function (response) {
                            if (response.d != '') {
                                return JSON.parse(response.d).length;
                            }
                            else {
                                return 0;
                            }
                        },
                        model: {
                            id: "CustomerID",
                            fields: {
                                CustomerID: { type: "string" },
                                CustomerCode: { type: "string", validation: { required: true} },
                                CustomerName: { type: "string", validation: { required: true} },
                                GradeName: { type: "string" },
                                Birthday: { type: "date", validation: { required: true} },
                                SpecialDay: { type: "date", validation: { required: true} },
                                CompanyCode: { type: "string" },
                                CreatedUserID: { type: "string" },
                                CreatedDate: { type: "date" },
                                BillingAddress: { type: "string", validation: { required: true} },
                                ShippingAddress: { type: "string", validation: { required: true} },
                                ContactPerson: { type: "string", validation: { required: true} },
                                PhoneNumber: { type: "string", validation: { required: true} },
                                Email: { type: "string", validation: { required: true} },
                                IsActive: { type: "boolean" },
                                TotalPoint: { type: "number" },
                                ExpiredPoint: { type: "number" },
                                UsedPoint: { type: "number" },
                                AvailablePoint: { type: "number" }
                            }
                        }
                    }
                },
                sortable: true,
                pageable: {refresh: true},
                filterable: true,
                reorderable: true,
                resizable: true,
                height: 450,
                selectable: "row",
                toolbar: [{ name: 'create', text: 'Add New Customer'},{name:'excel'}],
                 excel: {
                    fileName: "Customer List.xlsx",
                    filterable: true,
                    allPages: true
                },
                batch: true,
                columns: [{ field: "CustomerID", title: "ID", width: 80, hidden: true },
                            { field: "CustomerCode", title: "Code", width: 100 },
                            { field: "CustomerName", title: "Name" },
                            { field: "GradeName", title: "Grade", width: 130},
                            { field: "TotalPoint", title: "Total Point", width: 140, format: "{0:n}",type:"number", attributes: { style: "text-align:right;"}  },
                            { field: "ExpiredPoint", title: "Expired Point", width: 140, format: "{0:n}",type:"number", attributes: { style: "text-align:right;"}  },
                            { field: "UsedPoint", title: "Used Point", width: 140, format: "{0:n}",type:"number", attributes: { style: "text-align:right;"}  },
                            { field: "AvailablePoint", title: "Available Point", width: 140, format: "{0:n}",type:"number", attributes: { style: "text-align:right;"}  },
                            { field: "Birthday", title: "Birthday", hidden: true ,width: 100, format: "{0:MM/dd/yyyy}"},
                            { field: "SpecialDay", title: "SpecialDay", hidden: true, width: 100, format: "{0:MM/dd/yyyy}" },
                            { field: "CompanyCode", title: "Company Code", hidden: true },
                           { field: "CompanyCode", title: "Company Code", hidden: true },
                              <%if (bool.Parse(HttpContext.Current.Session["IsAdmin"].ToString())){%>
                            { field: "CompanyName", title: "Company Name", width: 180 },
                            <%}else{ %>
                             { field: "CompanyName", title: "Company Name", width: 180, hidden: true },
                            <%} %>
                            { field: "ContactPerson", title: "Contact Person", width: 200, hidden: true  },
                            { field: "PhoneNumber", title: "Phone", width: 100, hidden: true },
                            { field: "Email", title: "Email", width: 200, hidden: true },
                            { field: "BillingAddress", title: "Billing Address", hidden: true },
                            { field: "ShippingAddress", title: "Shipping Address", hidden: true },
                            { field: "IsActive", title: "Active", width: 100, attributes: { style: "text-align:center;"} },
                            { command: ["edit", { text: "Property Link", click: showLink}], title: "Action", width: "200px"}]
                , editable: {
                    mode: "popup",
                   template: $("#template").html(),
                    confirmation: "Are you sure you want to remove this customer?"
                },
                edit: function (e) {
                 $('#dllGrade').kendoDropDownList({
                        optionLabel: "[Select Grade]",
                        dataTextField: "GradeName",
                        dataValueField: "GradeID",
                        dataSource: {
                            data: jsonCustomerGrade
                        }
                    });
                    var editWindow = e.container.data("kendoWindow");
                    if (e.model.isNew()) {
                        e.container.data("kendoWindow").title('Add New Customer');
                        $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                        isInsert = true;
                    }
                    else {
                        e.container.data("kendoWindow").title('Edit Customer');
                        $('[name="CustomerID"]').attr("readonly", true);
                        $('[name="CustomerCode"]').attr("readonly", true);
                        isInsert = false;
                    }
                },
                remove: function (e) {
                },
                save: function (e) {
                    var that = this;
                    var num = 1;
                    var listTextBox = $("input:text");
                    for (var i = 0; i < listTextBox.length; i++) {
                        var name = listTextBox[i].name;
                         if(name.length>0)
                        {
                        oCustomer[name] = $("[name=" + name + "]").val();
                        }

                    }
                    var listCheckBox = $("input:checkbox");
                    for (var i = 0; i < listCheckBox.length; i++) {
                        var name = listCheckBox[i].name;
                         if(name.length>0)
                        {
                        if ($("[name=" + name + "]").is(':checked')) {
                            oCustomer.IsActive = 'true';
                        }
                        else {
                            oCustomer.IsActive = 'false';
                        }
                        }
                    }
                    oCustomer.GradeID = $("#dllGrade").val();
                    oCustomer.Email = $("[name=Email]").val();
                    //Update or Insert Customer
                    $.ajax({
                        type: "POST",
                        url: "Customer.aspx/UpdateCustomer",
                        data: JSON.stringify({
                            oCustomer: JSON.stringify(oCustomer),
                            isInsert: isInsert
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                               //Reload Data 
                                grid.dataSource.read();
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
                     this.refresh();
                }
            }).data("kendoGrid");
        });
       
        function showLink(e) {
            e.preventDefault();
            var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
            var wnd = $("#details")
                        .kendoWindow({
                            title: "Customer Property Link",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 705,
                            height: 550,
                            content: { type: "POST", url: "Customer-Property-Link.aspx?CustomerID=" + dataItem.CustomerID + "&CustomerCode=" + dataItem.CustomerCode + "&CustomerName=" + dataItem.CustomerName, data: { "customer": kendo.stringify(dataItem)} },
                            iframe: true
                        }).data("kendoWindow");
            wnd.center().open();
        }
    </script>
    <script type="text/x-kendo-template" id="template">  
     <div style="width: 400px;">
        <div class="k-edit-label" style="display: none;">
            <label for="CustomerID">
                ID</label></div>
        <div class="k-edit-field" data-container-for="CustomerID" style="display: none;">
            <input name="CustomerID" class="k-input k-textbox" type="text" readonly="readonly"
                data-bind="value:CustomerID"></div>
        <div class="k-edit-label" style="display: none;">
            <label for="CompanyCode">
                CompanyCode</label></div>
        <div class="k-edit-field" data-container-for="CompanyCode" style="display: none;">
            <input name="CompanyCode" class="k-input k-textbox" type="text" readonly="readonly"
                data-bind="value:CompanyCode"></div>
        <div class="k-edit-label">
            <label for="CustomerCode">
                Code</label></div>
        <div class="k-edit-field" data-container-for="CustomerCode">
            <input name="CustomerCode" class="k-input k-textbox" required="required" type="text"
                data-bind="value:CustomerCode"></div>
        <div class="k-edit-label">
            <label for="CustomerName">
                Name</label></div>
        <div class="k-edit-field" data-container-for="CustomerName">
            <input name="CustomerName" class="k-input k-textbox" required="required" type="text"
                data-bind="value:CustomerName"></div>
        <div class="k-edit-label" style="display: none;">
            <label for="Grade">
                Grade</label></div>
        <div data-container-for="GradeID" class="k-edit-field" style="display: none;">
            <input id="dllGrade" name="Grade" data-bind="value:GradeID">
        </div>
        <div class="k-edit-label">
            <label for="Birthday">
                Birthday</label></div>
        <div data-container-for="Birthday" class="k-edit-field">
            <input type="text" name="Birthday" required="required" data-type="date" data-bind="value:Birthday"
                data-role="datepicker"></div>
        <div class="k-edit-label">
            <label for="SpecialDay">
                SpecialDay</label></div>
        <div data-container-for="SpecialDay" class="k-edit-field">
            <input type="text" name="SpecialDay" required="required" data-type="date" data-bind="value:SpecialDay"
                data-role="datepicker"></div>
        <div class="k-edit-label">
            <label for="BillingAddress">
                Billing Address</label></div>
        <div class="k-edit-field" data-container-for="BillingAddress">
            <input name="BillingAddress" class="k-input k-textbox" required="required" type="text"
                data-bind="value:BillingAddress"></div>
        <div class="k-edit-label">
            <label for="ShippingAddress">
                Shipping Address</label></div>
        <div class="k-edit-field" data-container-for="ShippingAddress">
            <input name="ShippingAddress" class="k-input k-textbox" required="required" type="text"
                data-bind="value:ShippingAddress"></div>
        <div class="k-edit-label">
            <label for="ContactPerson">
                Contact Person</label></div>
        <div class="k-edit-field" data-container-for="ContactPerson">
            <input name="ContactPerson" class="k-input k-textbox" required="required" type="text"
                data-bind="value:ContactPerson"></div>
        <div class="k-edit-label">
            <label for="PhoneNumber">
                Contact Phone</label></div>
        <div class="k-edit-field" data-container-for="PhoneNumber">
            <input name="PhoneNumber" class="k-input k-textbox" required="required" type="text"
                data-bind="value:PhoneNumber"></div>
        <div class="k-edit-label">
            <label for="Email">
                Email</label></div>
        <div class="k-edit-field" data-container-for="Email">
            <input name="Email" class="k-input k-textbox" required="required" type="email" data-bind="value:Email"></div>
        <div class="k-edit-label">
            <label for="IsActive">
                Active</label></div>
        <div class="k-edit-field" data-container-for="IsActive">
            <input name="IsActive" type="checkbox" data-bind="checked:IsActive" data-type="boolean"></div>
    </div>
    </script>
    <div id="details">
    </div>
    <table style="width: 100%;" border="0">
        <tr>
            <td>
                Code
            </td>
            <td style="width: 20%;">
                <input type="text" class="k-input k-textbox" name="KeySearch" id="KeySearch" style="width: 90%;"  placeholder="key search"  />
            </td>
            <td>
               Search
            </td>
            <td style="width: 60%;">
                <input type="text" class="k-input k-textbox" name="KeyWords" id="KeyWords" style="width: 100%;"  placeholder="enter customer code or customer name" />
            </td>
            <td align="right">
                <button type="button" id="btnSave" onclick="Search();" class="k-button k-button-icontext k-primary"
                    style="width: 150px;">
                    <span class="k-icon k-i-search"></span>Find</button>
            </td>
        </tr>
    </table>
    <div style="position: absolute; z-index: 0; margin-right: 8px; margin-top: 8px;">
        <div id="grid">
        </div>
    </div>
   
</asp:Content>
